<template>

  <div class="container">
    <!-- Sub-Category2456 -->
    <!-- 面包屑 -->
    <subread></subread>
    <!-- 筛选区 -->
    <subFilter @filter-change='fliterchange'></subFilter>
     <sub-sort @sort-change='sortChangeFn'></sub-sort>
     <!-- 结果区 -->
     <!-- 分类关联商品 -->
         <div class="goods-list ">
             <ul>
             <li v-for="item in list" :key="item.id"><GoodsItem  :goods="item"    /></li>
            </ul>
         <XtxInfiniteLoading :loading='loading' :finished='finished'  @load="onLoad" ></XtxInfiniteLoading>
         </div>
      </div>

</template>
<script>
import { ref, watch } from 'vue'
import subread from './components/subread.vue'
import subFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import GoodsItem from '@/views/category/components/goods-item.vue'
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'

export default {
  name: 'SubCategory',
  components: {
    subread,
    subFilter,
    SubSort,
    GoodsItem
  },
  setup () {
    const route = useRoute()
    const loading = ref(false)
    const finished = ref(false)

    let data = {
      page: 1,
      pageSize: 20
    }

    const list = ref([])

    const onLoad = async () => {
      loading.value = true
      const { result } = await findSubCategoryGoods(data)
      loading.value = false

      list.value.push(...result.items)

      if (result.items.length < data.pageSize) {
        finished.value = true
        return
      }
      data.page++
    }

    watch(() => route.params.id, id => {
      list.value = []
      finished.value = false
      data = {
        categoryId: id,
        page: 1,
        pageSize: 20
      }
      onLoad()
    }, { immediate: true })

    const sortChangeFn = val => {
      list.value = []
      finished.value = false
      data = { ...data, ...val, page: 1 }
      onLoad()
    }

    const fliterchange = val => {
      list.value = []
      finished.value = false
      data = data = { ...data, ...val, page: 1 }
      onLoad()
    }
    return { sortChangeFn, loading, finished, onLoad, list, fliterchange }
  }

}
</script>
<style scoped lang="less">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}</style>
